<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: qupen
  Date: 2016/11/15
  Time: 17:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="../../include/head.jsp">
    <jsp:param name="title" value="班次列表"/>
</jsp:include>
<style>
    .datepicker.dropdown-menu {
        z-index: 9999 !important;
    }
</style>
<jsp:include page="../../include/tenant_header.jsp"/>

<jsp:include page="../../include/tenant_sidebar.jsp"/>
<div class="content-wrapper content-wrapper-bg">
    <section class="content-header">
        <h4 class="page-title" style="display: inline-block"><spring:message code="label.tenant.shift.list"/></h4>
        <a id="setting" class="btn btn-add" href="javascript:;" data-toggle="modal" data-target="#myModal"
           style="margin-left:84px;">
            <i class="fa fa-plus" style="margin-right: 3px"></i><spring:message code="label.tenant.shift.set"/>
        </a>
    </section>
    <section class="content">
        <div class="box box-primary table-header-line">
            <div class="box-body" style="padding: 0">
                <input class="hidden" id="deviceId" value="${deviceId}"/>
                <table class="table" id="shift_list">
                    <thead>
                    <tr>
                        <th><spring:message code="label.tenant.effective.start-stop.time"/></th>
                        <th><spring:message code="label.tenant.shift.period"/></th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
        </div>
        <%--</div>--%>
    </section>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
         data-backdrop="false" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">
                        <spring:message code="label.tenant.shift.set"/>
                    </h4>
                </div>
                <div class="modal-body">
                    <div style="background-color: #fff">
                        <div style="margin-bottom: 10px;">
                            <div class="pull-left" style="margin-bottom: 10px;">
                                <scan><spring:message code="label.tenant.shift.effective.start.date"/>:</scan>
                                <div class="sie-calendar-parent">
                                    <input type="text" readonly="readonly" class="form-control sie-calendar-input"
                                           id="start_time">
                                    <img src="/images/calendar.png" class="sie-calendar-img"/>
                                </div>
                            </div>
                            <div class="pull-right" style="margin-bottom: 10px;">
                                <scan><spring:message code="label.tenant.shift.effective.end.date"/>:</scan>
                                <div class="sie-calendar-parent">
                                    <input type="text" readonly="readonly" class="form-control sie-calendar-input"
                                           style="background-color: #fff" id="end_time">
                                    <img src="/images/calendar.png" class="sie-calendar-img"/>
                                </div>
                            </div>
                        </div>
                        <div>
                            <table class="table">
                                <thead>
                                <tr>
                                    <th><spring:message code="label.tenant.shift.name"/></th>
                                    <th><spring:message code="label.start.time"/></th>
                                    <th><spring:message code="label.end.time"/></th>
                                    <th>shift lead</th>
                                </tr>
                                </thead>
                                <tbody id="tbody">
                                <tr data-index="1">
                                    <td class="table-body" style="width: 25%;">
                                        <input data-type="shift-name" style="width: 80%;margin: auto;"
                                               class="form-control sie-input-border sie-input-uwh">
                                    </td>
                                    <td class="table-body" style="width: 25%;">
                                        <select data-type="shift-start" style="width: 80%;margin: auto;padding: 0 12px;"
                                                class="form-control sie-input-border sie-input-uwh"
                                                onchange="firstChoose(this.value);">
                                            <c:forEach begin="0" end="24" step="1" varStatus="status">
                                                <c:if test="${status.index<9}">
                                                    <option value="${status.index}">0${status.index}:00:00</option>
                                                </c:if>
                                                <c:if test="${status.index>9}">
                                                    <c:choose>
                                                        <c:when test="${status.index==24}">
                                                            <option value="${status.index}">${status.index}:00:00
                                                            </option>
                                                        </c:when>
                                                        <c:otherwise>
                                                            <option value="${status.index}">${status.index}:00:00</option>
                                                        </c:otherwise>
                                                    </c:choose>
                                                </c:if>
                                            </c:forEach>
                                        </select>
                                    </td>
                                    <td class="table-body" style="width: 25%;">
                                        <select id="firstTr" data-type="shift-end"
                                                style="width: 80%;margin: auto;padding: 0 12px;"
                                                class="form-control sie-input-border sie-input-uwh"
                                                onchange="addrow(this.value,this)">

                                        </select>
                                    </td>
                                    <td class="table-body" style="width: 25%;">
                                        <input data-type="shift-user" style="width: 80%;margin: auto;"
                                               class="form-control sie-input-border sie-input-uwh">
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button id="cancel" type="button" class="btn btn-default" data-dismiss="modal"><spring:message
                            code="label.cancel"/>
                    </button>
                    <button id="create" type="button" class="btn btn-primary">
                        <spring:message code="label.admin.confirm"/>
                    </button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
</div>
<jsp:include page="../../include/foot.jsp"/>
<script>
    $(document).ready(function () {
        var table = $('#shift_list').DataTable({
            "dom": '<"datatable-header"<"dataTables_filter">l><"datatable-scroll"t><"datatable-footer dataTable-footer-padding"<"pull-left"i><"pull-right"p>>',
            paging: true,
            lengthChange: false,
            ordering: true,
            autoWidth: false,
            info: true,
            serverSide: false,
            fixedHeader: true,
            searching: true,
            aLengthMenu: [15],
            ajax: {
                url: '/partner/{tenant}/api/v1/shift/list'.replace("{tenant}", getKeyByUrl()),
                data: {
                    deviceId: $("#deviceId").val()
                },
                dataSrc: 'data'
            },
            columns: [
                {
                    data: 'begin_date',
                    "render": function (data, type, full, meta) {
                        return data + " - " + full.end_date;
                    }
                },
                {
                    data: 'width', width: "60%",
                    "render": function (data, type, full, meta) {
                        var widthArray = data.split(",");
                        var validTime =full.validTime.split(",");
                        var color = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570'];
                        var line = $("<div></div>");
                        var _color;
                        for (var i = 0; i < validTime.length; i++) {
                            if (i.toString().length == 1) {
                                _color = color[i];
                            } else {
                                _color = color[parseInt(i.toString().substr(-1))];
                            }
                            var width = widthArray[i] / (24/100) + "%";
                            var $a = $("<a></a>").attr("style", "width:" + width + ";position:relative;background-color:" + _color + ";display:inline-block;height:30px;border-right:1px solid #fff").attr("onmouseover", "showTime(this)").attr("href", "javascript:;").attr("onmouseout", "removeTime(this)").attr("data-time", validTime[i]);
                            line.append($a);
                        }
                        return line.html();
                    }
                }
            ],
            "language": {url: '/lang/datatable.chs.json'}
        });
        $('#inputSuccess2').bind('keyup', function (e) {
            table.search(this.value).draw();
        });

        firstChoose(0);
    });
    var initResultArray;
    $(document).ready(function () {
        $('#start_time').datepicker({
            language: "zh-CN",
            autoclose: true,
            format: "yyyy-mm-dd",
            startDate: new Date(),
            todayHighlight: true
        }).on("changeDate", function (ve) {
            $('#end_time').datepicker('setStartDate', ve.date)
        });

        $('#end_time').datepicker({
            language: "zh-CN",
            autoclose: true,
            format: "yyyy-mm-dd",
            startDate: new Date(),
            todayHighlight: true
        }).on("changeDate", function (ve) {
            $('#start_time').datepicker('setEndDate', ve.date)
        });
        bindDateInputClickEvent();
        $("#cancel").click(function () {
            $('#start_time').val("");
            $('#end_time').val("");
            $("#tbody").find("tr:first").find("td [data-type='shift-end']").find('option[value="24:00"]').attr("selected", "selected");
            $("#tbody").find("tr:first").find("td [data-type='shift-name']").val("");
            $("#tbody").find("tr:first").find("td [data-type='shift-user']").val("");
            while ($("#tbody").find("tr:first").next().length > 0) {
                $("#tbody").find("tr:first").next().remove();
            }
            firstChoose(0);
            $("#tbody tr:first select:first option:first").attr("selected",true);
            $("#myModal").modal('hide');
        });

        $("#create").click(function () {
            if ($("#start_time").val() == null || $("#start_time").val() == '') {
                swal('<spring:message code="label.tenant.please.choice.effective.start.date"/>', "", "warning");
                return;
            }
            if ($("#end_time").val() == null || $("#end_time").val() == '') {
                swal('<spring:message code="label.tenant.please.choice.effective.end.date"/>', "", "warning");
                return;
            }

            var shiftArr = [];
            var trs = $("#tbody tr");
            $.each(trs, function (index, tr) {
                var tds = $(tr).find("td");
                var shift = {};
                $.each(tds, function (index, td) {
                    var $row = $(td);
                    var type = $row.children().data("type");
                    if ($row.children().data("type") == "shift-name" || $row.children().data("type") == "shift-user") {
                        shift[type] = $row.children().val();
                    } else {
                        shift[type] = $row.children().find("option:selected").text();
                    }
                });
                shiftArr.push(shift);
            });
            $.ajax({
                url: "/partner/{tenant}/api/v1/shift/add".replace("{tenant}", getKeyByUrl()),
                type: "post",
                data: JSON.stringify({
                    deviceId: $("#deviceId").val(),
                    startDate: $('#start_time').val(),
                    endDate: $('#end_time').val(),
                    shift: shiftArr
                }),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    $('#start_time').val("");
                    $('#end_time').val("");
                    $("#tbody").find("tr:first").find("td [data-type='shift-end']").find('option[value="24:00"]').attr("selected", "selected");
                    $("#tbody").find("tr:first").find("td [data-type='shift-name']").val("");
                    $("#tbody").find("tr:first").find("td [data-type='shift-user']").val("");
                    while ($("#tbody").find("tr:first").next().length > 0) {
                        $("#tbody").find("tr:first").next().remove();
                    }
                    firstChoose(0);
                    $("#myModal").modal('hide');
                    $('#shift_list').DataTable().ajax.reload();
                },
                error: function (e) {
                    console.log(e);
                    swal("Error!", "", "error");
                }
            });
        });
    });

    function showTime(_this) {
        var message = $(_this).data("time");
        $(_this).append($('<div class="message-box message-box-change" style="width:200px;"></div>').text(message).append($('<div class="triangle-border tb-border"></div><div class="triangle-border tb-background"></div>')));
    }

    function removeTime(_this) {
        $(_this).children().remove()
    }

    function addrow(index, _this) {
        var index_int = parseInt(index);
        if (index_int == initResultArray.length-1) {
            var thisTr = $(_this).parent().parent().data("index");
            var trs = $("#tbody").find("tr");
            for (var i = 0; i < trs.length; i++) {
                if ($(trs[i]).data("index") > thisTr) {
                    $(trs[i]).remove();
                }
            }
        } else {
            var this_array = initResultArray.slice(index_int,initResultArray.length);
            var thisTr = $(_this).parent().parent().data("index");
            var trs = $("#tbody").find("tr");
            for (var j = 0; j < trs.length; j++) {
                if ($(trs[j]).data("index") > thisTr) {
                    $(trs[j]).remove();
                }
            }
            var start_text = this_array.splice(0,1);
            var $selectStart = $("<select></select>").addClass("form-control sie-input-border sie-input-uwh").attr("data-type", "shift-start").attr("style", "width: 80%;margin: auto;padding: 0 12px;").append($("<option></option>").text(start_text[0]<10?"0" +start_text[0] + ":00:00":start_text[0] + ":00:00"));
            var $selectEnd = $("<select></select>").addClass("form-control sie-input-border sie-input-uwh").attr("data-type", "shift-end").attr("style", "width: 80%;margin: auto;padding: 0 12px;").attr("onchange", "addrow(this.value,this)");

            for (var z =0; z < this_array.length; z++) {
                if (this_array[z] < 10) {
                    if (z == this_array.length-1) {
                        $selectEnd.append($("<option></option>").text("0" +this_array[z] + ":00:00").attr("value", z+index_int+1));
                    } else {
                        $selectEnd.append($("<option></option>").text("0" +this_array[z] + ":00:00").attr("value", z+index_int+1));
                    }
                } else {
                    if (z == this_array.length-1) {
                        $selectEnd.append($("<option></option>").text(this_array[z] + ":00:00").attr("value", z+index_int+1).attr("selected", true));
                    } else {
                        $selectEnd.append($("<option></option>").text(this_array[z] + ":00:00").attr("value", z+index_int+1));
                    }
                }
            }
            var $tr = $("#tbody").find("tr:last");
            var newInput = $("<tr></tr>").addClass("add-row").attr("data-index", parseInt($tr.data("index")) + 1).append(
                    $("<td></td>").addClass("table-body").attr("style", "width:25%").append(
                            $("<input/>").attr("data-type", "shift-name").addClass("form-control sie-input-border sie-input-uwh").attr("style", "width: 80%;margin: auto"))).append(
                    $("<td></td>").addClass("table-body").attr("style", "width:25%").append($selectStart)).append(
                    $("<td></td>").addClass("table-body").attr("style", "width:25%").append($selectEnd)).append(
                    $("<td></td>").addClass("table-body").attr("style", "width:25%").append($("<input/>").attr("data-type", "shift-user").addClass("form-control sie-input-border sie-input-uwh").attr("style", "width: 80%;margin: auto")));

            $tr.after(newInput);
        }
    }

    function firstChoose(index) {
        var dateArray = initDateArray();
        dateArray.pop();
        var spliceDateArray = dateArray.splice(0, parseInt(index) + 1);
        var concatDateArray = dateArray.concat(spliceDateArray);
        initResultArray = concatDateArray;
        $("#firstTr").html("");
        $(".add-row").remove();
        $("#firstTr").append($("<option></option>").text("请选择"));
        for (var i = 0; i < concatDateArray.length; i++) {
            $("#firstTr").append($("<option></option>").attr("value", i).text(concatDateArray[i]<10?"0"+concatDateArray[i]+":00:00":concatDateArray[i]+":00:00"));
        }
    }

    function initDateArray() {
        var initArray = [];
        for (var i = 0; i < 25; i++) {
            initArray.push(i);
        }
        return initArray;
    }
</script>